package com.tuiyun.jxgl.action;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.transaction.annotation.Transactional;

import com.tuiyun.jxgl.bean.Driver;
import com.tuiyun.jxgl.bean.Student;
import com.tuiyun.jxgl.bean.Stuselectdriver;
import com.tuiyun.jxgl.dao.DriverHome;
import com.tuiyun.jxgl.dao.StuselectdriverHome;

public class CommentDriverAction {
	
	private int driverid;
	private byte rate;
	private byte attitude;
	private byte effect;
	private String comment;
	public int getDriverid() {
		return driverid;
	}

	public void setDriverid(int driverid) {
		this.driverid = driverid;
	}

	

	public byte getRate() {
		return rate;
	}

	public void setRate(byte rate) {
		this.rate = rate;
	}

	public byte getAttitude() {
		return attitude;
	}

	public void setAttitude(byte attitude) {
		this.attitude = attitude;
	}

	public byte getEffect() {
		return effect;
	}

	public void setEffect(byte effect) {
		this.effect = effect;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public StuselectdriverHome getSsh() {
		return ssh;
	}

	public void setSsh(StuselectdriverHome ssh) {
		this.ssh = ssh;
	}

	private StuselectdriverHome ssh;
	private DriverHome dh;
	
	@Transactional
	public String execute(){
		Subject s = SecurityUtils.getSubject();
		if(s.isAuthenticated()){
			Object o = s.getPrincipal();
			if(o instanceof Student){
				Student stu = (Student)o;
				Stuselectdriver sd = ssh.findByStudent(stu.getId());
				if(sd != null && sd.getDriver().getId().intValue() == driverid && sd.getComment_time() == null){
					sd.setAttitude((attitude));
					sd.setComment(comment);
					sd.setComment_time(new Date(System.currentTimeMillis()));
					sd.setEffect((effect));
					sd.setRate((rate));
					ssh.attachDirty(sd);
					
					//udpate driver rate
					List<Stuselectdriver> ss = ssh.findbyDriver(driverid);
					int size = 12;
					int sum = 12*4;
					for(Stuselectdriver t : ss){
						if(t.getComment_time() != null){
							size ++;
							sum += t.getRate();
						}
					}
					Driver dri = dh.findById(driverid);
					if(size != 0){
						dri.setRate(sum*1.0f/size);
						dh.attachDirty(dri);
					}
					return "success";
				}
			}
		}
		return "success";
	}

	public DriverHome getDh() {
		return dh;
	}

	public void setDh(DriverHome dh) {
		this.dh = dh;
	}

}
